package com.paiai.lslease.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.opensymphony.xwork2.ActionSupport;
import com.paiai.lslease.service.appuser.AppSysUserService;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class BaseAction extends ActionSupport implements ServletRequestAware {

	private static final Logger logger = LoggerFactory.getLogger(BaseAction.class);
	
	public static final String FORMATTER = "yyyy-MM-dd HH:mm";
	public static final String FORMATTER1 = "yyyy年MM月dd日 HH:mm";
	public static final String FORMATTER2 = "yyyy-MM-dd";
	public static final String FORMATTER12 = "yyyy年MM月dd日";

	private static final long serialVersionUID = 1L;

	protected HttpServletRequest request;
	public static String basePath;
	public static String projectPath;

	public AppSysUserService appSysUserService;

	public void setAppSysUserService(AppSysUserService appSysUserService) {
		this.appSysUserService = appSysUserService;
	}

	public BaseAction() {
		basePath = ServletActionContext.getServletContext().getRealPath("/");
		projectPath = ServletActionContext.getServletContext().getContextPath();
	}

	public static final ResourceBundle rbEn;
	public static final ResourceBundle rbCh;

	static {
		rbEn = ResourceBundle.getBundle("i18n/resources", Locale.US);
		rbCh = ResourceBundle.getBundle("i18n/resources", Locale.CHINA);
	}

	/**
	 * 向客户端发送数据
	 */
	public void sendMsg(String content) {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "*");
			response.setHeader("Content-type", "text/html;charset=UTF-8"); 
			response.setCharacterEncoding("UTF-8");
			logger.debug(content);
			response.getWriter().write(content);
		} catch (Exception ee) {
			ee.printStackTrace();
		}
	}

	/**
	 * 返回成功信息
	 */
	public void sendSuccesseMsg(String msg){
		sendSuccesseMsg(null, msg);
	}
	
	/**
	 * 返回成功信息
	 */
    public void sendSuccesseMsg(Object data ,String msg){
    	sendSuccesseMsg(1, data, msg);
	}

	/**
	 * 返回成功信息
	 */
	public void sendSuccesseMsg(int status, Object data ,String msg){
		List<Object> list ;
		if(data == null || data instanceof String){
			sendResultMsg(new AppResult(status,msg,data));
		}else  if(!(data instanceof List)){
			list = new ArrayList<Object>();
			list.add(data);
			sendResultMsg(new AppResult(status,msg,list));
		}else{
			sendResultMsg(new AppResult(status,msg,data));
		}
	}

    /**
     * 返回失败信息
     */
    public void sendFailureMsg(String error){
    	sendResultMsg(AppResult.newFailResult(error));
    }
    
    /**
     * 返回带数据的失败信息
     */
    public void sendFailureMsg(Object data, String error){
        data = (data == null) ? "" : data;
	    if( data instanceof String){
	    	sendResultMsg(AppResult.newFailResult(error,data));
    	}else if(!(data instanceof List)){
    		List<Object> list ;
			list = new ArrayList<Object>();
			list.add(data);
			sendResultMsg(AppResult.newFailResult(error,list));
		}else{
			sendResultMsg(AppResult.newFailResult(error,data));
		}
    }

	/**
	 * 返回特定格式的自定义信息
	 */
	public void sendResultMsg(AppResult result){
		String mess = JSON.toJSONStringWithDateFormat(result, FORMATTER, SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullNumberAsZero,SerializerFeature.WriteNullStringAsEmpty);
		sendMsg(mess);
	}

	/**
	 * 返回自定义信息
	 */
	public void sendResultMsgFormat(AppResult result,String format){
		String mess = JSON.toJSONStringWithDateFormat(result, format, SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullNumberAsZero,SerializerFeature.WriteNullStringAsEmpty);
		sendMsg(mess);
	}

	/**
	 * 获取当前语言环境对应的文本
	 */
	protected String getLanguageValue(String key) {
		int code = getLanguageCode();
		switch (code) {
		case 1:
			return rbCh.getString(key);
		case 2:
			return rbEn.getString(key);
		default:
			return rbCh.getString(key);
		}
	}

	/**
	 * 获取语言码
	 */
	public int getLanguageCode() {
		String lan = request.getLocale().getLanguage().toLowerCase();
		String lanAccept = request.getHeader("accept-language");
		logger.debug("getLanguageCode：{},lanAccept：{}", lan, lanAccept);

		if (lanAccept != null && lanAccept.startsWith("zh") || lan.contains("zh")) {
			return 1;
		} else if (lanAccept != null && lanAccept.startsWith("en") || lan.contains("en")) {
			return 2;
		} else {
			return 1;
		}
	}

	/**
	 * 获取语言名称
	 */
   	public String getLanguageName(){
		String lan = request.getLocale().getLanguage().toLowerCase();
		String lanAccept = request.getHeader("accept-language");
		logger.debug("getLanguageCode："+lan+"--lanAccept："+lanAccept);

		if(lanAccept != null && lanAccept.startsWith("zh") || lan.contains("zh")){
		  return "ZH";
		}else if(lanAccept != null && lanAccept.startsWith("en") || lan.contains("en")){
		  return "EN";
		}else{
		  return "ZH";
		}
  }
	
	public synchronized HttpServletRequest getRequest() {
		return request;
	}

	public synchronized void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletRequest(HttpServletRequest arg0) {
		this.setRequest(arg0);
	}
}